package com.lianxueda.drawing.controller;


import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lianxueda.drawing.common.R;
import com.lianxueda.drawing.domain.dto.AddCourse;
import com.lianxueda.drawing.domain.dto.StudentFromDTO;
import com.lianxueda.drawing.domain.dto.StudentQueryDTO;
import com.lianxueda.drawing.domain.pojo.CourseStudent;
import com.lianxueda.drawing.domain.pojo.Courses;
import com.lianxueda.drawing.domain.pojo.Students;
import com.lianxueda.drawing.domain.vo.PageVO;
import com.lianxueda.drawing.domain.vo.StudentCourseVO;
import com.lianxueda.drawing.mapper.CourseStudentMapper;
import com.lianxueda.drawing.mapper.StudentsMapper;
import com.lianxueda.drawing.service.CourseStudentService;
import com.lianxueda.drawing.service.CoursesService;
import com.lianxueda.drawing.service.StudentsService;

import com.lianxueda.drawing.service.WxUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/student")
@Tag(name = "学生管理", description = "学生管理")
@Slf4j
public class StudentController {
    @Resource
    private StudentsService studentsService;
    @Resource
    private CoursesService courseService;
    @Resource
    private WxUserService wxUserService;
    @Resource
    private StudentsMapper studentsMapper;


    @Resource
    private CourseStudentService courseStudentService;
    @Resource
    private CourseStudentMapper courseStudentMapper;
    @Operation(summary = "查询学生列表")
    @PostMapping("/getStudent")
    public R getStudent(@RequestBody StudentQueryDTO studentQueryDTO){
        //使用Lambda表达式【指定需要查询的字段】
        IPage<Students> page = new Page<>(studentQueryDTO.getCurPage(),
                studentQueryDTO.getPageSize());
        //2.设置查询条件
        QueryWrapper<Students> queryWrapper = new QueryWrapper<>();
        //考生姓名
        queryWrapper.lambda().like(StringUtils.isNotBlank(
                        studentQueryDTO.getName()),
                Students::getName,
                studentQueryDTO.getName());

        //性别
        queryWrapper.lambda().eq(studentQueryDTO.getGender()!=null,
                Students::getGender,
                studentQueryDTO.getGender());

        //家长电话
        queryWrapper.lambda().like(StringUtils.isNotBlank(studentQueryDTO.getParentPhone()),
                Students::getParentPhone,
                studentQueryDTO.getParentPhone());



        //查询指定字段
        //queryWrapper.select("id", "title");
        //排除字段查询
        queryWrapper.select(Students.class, info -> !info.getColumn().equals("deleted"));
        queryWrapper.orderByDesc("id");
        //3.查询
        IPage<Students> pageResult = studentsService.page(page, queryWrapper);
        //遍历根据
        List<Students> studentsList = pageResult.getRecords();

        // 4. 遍历学生列表，查询每个学生的课程名称，并封装到 StudentCourseDTO 中
        List<StudentCourseVO> studentCourseVOList = new ArrayList<>();
        for (Students student : studentsList) {
            StudentCourseVO studentCourseVO = new StudentCourseVO();
            BeanUtils.copyProperties(student, studentCourseVO);

            // 根据 student_id 查询课程名称列表
            List<String> courseNames = studentsMapper.getCourseNamesByStudentId(student.getId());
            studentCourseVO.setCourse(courseNames);

            studentCourseVOList.add(studentCourseVO);
        }



        //4.封装，返回
//        PageVO pageVo = new PageVO<>();
        PageVO<StudentCourseVO> pageVo = new PageVO<>();
        pageVo.setTotal(pageResult.getTotal());
        pageVo.setList(studentCourseVOList);

        pageVo.setPageSize(pageResult.getSize());
        pageVo.setCurrentPage(pageResult.getCurrent());


        return R.suc(pageVo);

    }
    @PostMapping("/addStudent")
    @Operation(summary = "添加学生信息")
    public R addStudent(@RequestBody StudentFromDTO studentFromDTO) {
        Students students = new Students();
        students.setName(studentFromDTO.getName());
        students.setGender(studentFromDTO.getGender());
        students.setParentPhone(studentFromDTO.getParentPhone());
        students.setCreateTime(new Date());
        students.setUpdatedTime(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate;
        try {
            birthDate = simpleDateFormat.parse(studentFromDTO.getBirthDate());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        students.setBirthDate(birthDate);
        students.setDeleted(0);
        students.setRemark(studentFromDTO.getRemark());
        studentsService.save(students);

        return R.suc("添加成功");


    }
    @PostMapping("/updateStudent")
    @Operation(summary = "修改学生信息")
    public R updateStudent(@RequestBody StudentFromDTO studentFromDTO) {
        Students students = new Students();
        students.setId(studentFromDTO.getId());
        students.setName(studentFromDTO.getName());
        students.setGender(studentFromDTO.getGender());
//        Integer parentId = wxUserService.selectIdByName(studentFromDTO.getParentName());
        students.setParentPhone(studentFromDTO.getParentPhone());
        students.setCreateTime(new Date());
        students.setUpdatedTime(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate;
        try {
            birthDate = simpleDateFormat.parse(studentFromDTO.getBirthDate());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        students.setBirthDate(birthDate);
        students.setDeleted(0);
        students.setRemark(studentFromDTO.getRemark());
        studentsService.updateById(students);
        return R.suc("修改成功");
    }
    @DeleteMapping("/deleteStudent")
    @Operation(summary = "删除学生信息")
    public R deleteStudent(@RequestParam("id") Integer id) {
        studentsService.removeById(id);
        //根据id从CourseStudent表中删除所有的课程
        courseStudentMapper.delete(new QueryWrapper<CourseStudent>().eq("student_id", id));
        return R.suc("删除成功");
    }

    //根据id从CourseStudent表中查询课程course_id;然后在courses表中查询课程名称

    @PostMapping("/getCourse")
    @Operation(summary = "根据id从CourseStudent表中查询课程course_id，然后在courses表中查询课程名称")
    public R getCourse(@RequestParam("id") Integer student_id) {
        // 从 CourseStudent 表中查询 course_id 列表
        List<Integer> courseIds = courseStudentService.selectCourseId(student_id);
        System.out.println(student_id);
        System.out.println(courseIds);
        if (courseIds == null || courseIds.isEmpty()) {
            return R.suc(null);
        }

        // 根据 course_id 列表在 Courses 表中查询课程名称
        List<Courses> courses = courseService.selectCourseByIds(courseIds);
        // 将结果封装到 R 对象并返回
        return R.suc(courses);
    }

    @PostMapping("/getCourseById")
    @Operation(summary = "根据id从courses表中查询课程名称")
    public R getCourseName(@RequestParam Integer id) {
        Courses courses = courseService.getCoursesById(id);
        //遍历courses
        if(courses != null){
            System.out.println("ddddddddddddd");
        }

        return R.suc(courses);
    }

    //学生删除课程的接口
    @DeleteMapping("/deleteCourse")
    @Operation(summary = "学生删除课程的接口")
    public R deleteCourse(@RequestParam("studentId") Integer studentId, @RequestParam("courseName") String courseName) {
        // 根据课程名称在courses表中查询课程id，然后删除class_courses表中的的studentId与courseId
        Integer courseId = courseService.getCourseIdByName(courseName);
        if (courseId != null) {
            courseStudentMapper.delete(new QueryWrapper<CourseStudent>().eq("student_id", studentId).eq("course_id", courseId));
            return R.suc("删除成功");
        } else {
            return R.fail("删除失败");
        }

    }


    //学生购买课程的接口
    @PostMapping("/buyCourse")
    @Operation(summary = "学生购买课程的接口")
    public R buyCourse(@RequestBody AddCourse addCourse) {
        String name = addCourse.getName();
        Integer studentId = addCourse.getStudentId();

        // 根据课程名称查询课程ID
        Integer courseId = courseService.getCourseIdByName(name);

        if (courseId == null) {
            return R.fail("课程不存在");
        }

        // 将学生ID和课程ID插入到 course_student 表中
        int result = courseStudentService.addCourseForStudent(studentId, courseId);

        if (result > 0) {
            return R.suc("课程购买成功");
        } else {
            return R.fail("购买失败");
        }
    }




}
